package cn.hyy.FVOnline.controller;

import cn.hyy.FVOnline.entity.User;
import cn.hyy.FVOnline.entity.PageEntitys;
import cn.hyy.FVOnline.service.UserService;
import cn.hyy.FVOnline.utils.MD5Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController{

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/register", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String register(@RequestParam("telephone")String telephone, @RequestParam("password")String password, @RequestParam("phoneCode")String phoneCode, HttpServletResponse response, HttpSession session){

        JSONObject jo = new JSONObject();
        User user = new User();
        user.setTelephone(telephone);
        user.setPassword(MD5Util.encrypt(password));
        userService.register(user);
        User loginUser = userService.findByTelephonePassword(user);
        if (loginUser != null){
            Cookie cookie  = new Cookie("userId",loginUser.getId().toString());
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 *30);
            response.addCookie(cookie);
            jo.put("code","success");
            jo.put("message","登录成功");
        }
        return jo.toJSONString();
    }

    @RequestMapping(value = "/login", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String login(@RequestParam("telephone") String telephone, @RequestParam("password")String password, @RequestParam("phoneCode")String phoneCode, HttpServletResponse response, HttpSession session){

        JSONObject jo = new JSONObject();
        //查询数据库判断是否登陆成功。
        User user = new User();
        user.setTelephone(telephone);
        user.setPassword(MD5Util.encrypt(password));
        User loginUser = userService.findByTelephonePassword(user);
        //登陆成功，设置客户端Cookie保存用户登录信息，保存时间为一个月
        if (loginUser.getLevel() == 1){
            jo.put("code","level");
        }else {
            if (loginUser != null){
                Cookie cookie  = new Cookie("userId",loginUser.getId().toString());
                cookie.setPath("/");
                cookie.setMaxAge(60 * 60 * 24 *30);
                response.addCookie(cookie);
                jo.put("code","success");
                jo.put("message","登录成功");
            }else {
                jo.put("code","error");
                jo.put("message","密码错误");
            }
        }
        return jo.toJSONString();
    }

    @RequestMapping(value = "/information", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String information(@RequestParam("userId") String userId){

        User user = new User();
        user.setId(Integer.parseInt(userId));

        User information = userService.findById(user);

        information.setPassword(null);

        return JSON.toJSONString(information);
    }

    @RequestMapping("/getHS")
    public @ResponseBody void getHS(@RequestParam("userId") String userId, HttpServletResponse response){

        try {

            BufferedImage bi = userService.findHS(userId);

            ImageIO.write(bi,"PNG",response.getOutputStream());
        }catch (Exception e){
            System.out.println(e);
        }

    }

    @RequestMapping(value = "/updateInformation", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String updateInformation(@RequestParam("userId") String userId,@RequestParam("username") String username,
                                    @RequestParam("name") String name, @RequestParam("sex") String sex,
                                    @RequestParam("birthday") String birthday){

        JSONObject jo = new JSONObject();
        try {
            if (username.length() == 0){
                username = null;
            }
            if (name.length() == 0){
                name = null;
            }
            if (sex.length() == 0){
                sex = null;
            }
            if (birthday.length() == 0){
                birthday = null;
            }
            User user = new User();
            user.setId(Integer.parseInt(userId));
            user.setUsername(username);
            user.setName(name);
            user.setSex(sex);
            user.setBirthday(birthday);
            userService.updateInformation(user);
            jo.put("code","success");
            jo.put("message","修改成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return jo.toJSONString();
    }

    @RequestMapping(value = "/updatePassword", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String updatePassword(@RequestParam("userId") String userId,@RequestParam("password") String password){

        JSONObject jo = new JSONObject();
        try {

            User user = new User();

            user.setId(Integer.parseInt(userId));
            user.setPassword(MD5Util.encrypt(password));

            userService.updatePassword(user);

            jo.put("code","success");
            jo.put("message","修改成功");

        }catch (Exception e){

        }

        return jo.toJSONString();
    }

    @RequestMapping(value = "/updateHS", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String updateHS(@RequestParam(value = "userId") String userId,@RequestParam(value = "file",required=false) MultipartFile file){

        JSONObject jo = new JSONObject();
        try {
            userService.updateHS(userId,file);
            jo.put("code","success");
            jo.put("message","修改成功");
        }catch (Exception e){
        }
        return jo.toJSONString();
    }

    @RequestMapping(value = "/getUser", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String getUser(@RequestParam("what")String what,@RequestParam("page")String page,@RequestParam("pageSize")String pageSize){
        PageEntitys pageEntitys = userService.getUser(what, Integer.parseInt(page), Integer.parseInt(pageSize));
        return JSONObject.toJSONString(pageEntitys);
    }

    @RequestMapping(value = "/delUser", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String delUser(@RequestParam("id")String id){
        JSONObject jo = new JSONObject();
        try {
            userService.delUser(Integer.parseInt(id));
            jo.put("code","success");
        }catch (Exception e){
            jo.put("code","error");
        }
        return jo.toJSONString();
    }

}
